package com.changgou.seckill.task;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: 大佬味的小男孩
 * @date: 2020-08-07 15:34
 **/
@Component
public class SeckillGoodsPushTask {
    /*
        1）获取秒杀时间段菜单信息
        2）遍历每一个时间段，添加该时间段下秒杀商品
            2.1）将当前时间段转换为String，作为redis中的key
            2.2）查询商品信息（状态为1，库存大于0，秒杀商品开始时间大于当前时间段，秒杀商品结束时间小于当前时间段，
                当前商品的id不在redis中）
        3）添加redis

     */
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String SECKILL_GOODS_KEY="seckill_goods_";

    @Scheduled(cron = "0/30 * * * * ?") //暂定为30秒一次，正常业务为每天凌晨触发
    public void loadSecKillGoodsToRedis() {
        List<Date> dateMenus = DateUtil.getDateMenus();//5个时间段  第一个元素为当前时间段
        for (Date dateMenu : dateMenus) {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String redisExName = DateUtil.date2Str(dateMenu); //格式转换

            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");  //审核状态为1
            criteria.andGreaterThan("stockCount",0); //库存大于0
            criteria.andGreaterThanOrEqualTo("startTime",simpleDateFormat.format(dateMenu)) ; //秒杀商品开始时间>=当前时间段
            criteria.andLessThan("endTime",simpleDateFormat.format(DateUtil.addDateHour(dateMenu,2))); //秒杀商品结束<当前时间段+2小时


            Set keys = redisTemplate.boundHashOps(SECKILL_GOODS_KEY + redisExName).keys();  // key field value

            //排除之前已经加载到Redis缓存中的商品数据
            if (keys != null && keys.size()>0){
                criteria.andNotIn("id",keys);
            }

            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);

            //添加到缓存中
            for (SeckillGoods seckillGoods : seckillGoodsList) {
                redisTemplate.opsForHash().put(SECKILL_GOODS_KEY + redisExName,seckillGoods.getId(),seckillGoods);
            }
        }


    }

}
